//调用	import iosCheckOrder from '@/js/iosPay.js'
import post from './http.js'
const Init = () => {
	return new Promise((resolve, reject) => {
		//使用uni.getProvider来获取通道
		uni.getProvider({
			service: 'payment',
			success: (res) => {
				let iapChannel = res.providers.find((channel) => {
					return (channel.id === 'appleiap')
				})
				//成功之后会返回通道
				if(iapChannel){
					resolve(iapChannel)
				}
			},
		})
	})
}

const restore = (iapChannel) => {
	console.log("获取苹果服务器已支付且未关闭的交易列表")
	return new Promise((resolve, reject) => {
		iapChannel.restoreCompletedTransactions({
			manualFinishTransaction: true,
			username: ''
		}, (res) => {
			console.log('===restore==success==', err)
			resolve(res)
		}, (err) => {
			console.log('===restore==error==', err)
			reject(err);
		})
	});
}

const finishTransaction = (transaction, iapChannel) => {
	console.log("关闭订单")
	return new Promise((resolve, reject) => {
		iapChannel.finishTransaction(transaction, (res) => {
			console.log("关闭订单成功", res)
			resolve(res);
		}, (err) => {
			reject(err);
		});
	});
}

const getReview = (iapChannel) => {
	//请求是否有已完成未关闭的订单
	console.log('请求是否有已完成未关闭的订单', iapChannel)
	restore(iapChannel).then(res => {
		//如果有并且状态为已支付则请求关闭并回调给后端
		console.log('已支付请求关闭的订单', res)
		if (res.length > 0) {
			//轮询关闭订单
			res.map(item => {
				//如果状态为已完成的状态
				const orderId = item.payment.username || ''
				
				const transactionState = parseInt(item.transactionState);
				if (!orderId || transactionState === 2) {
					finishTransaction(item, iapChannel)
				} else if (transactionState === 1) {
					//后端逻辑，此处省略，通常是完成上报凭证的操作，来完成补单
					//请求后端接口上传支付凭证 
					let orderString = item
					if (typeof orderString == "object") {
						orderString = JSON.stringify(orderString)
					}
					post("pay/applePayBack", {
						orderId: orderId,
						orderString: orderString
					}).then(ret => {
						finishTransaction(item, iapChannel)
					})
				}
			})
		}
	})
}

function iosCheckOrder() {
	return Init()
		.then(iapChannel => getReview(iapChannel))
}

export default iosCheckOrder;